<?php

namespace dingdong\utils;

class SqlBuilder
{
    public static function query($table, $param = [], $field = '*')
    {
        $sql = 'SELECT ' . $field . ' FROM `' . $table . '` WHERE 1=1 ';
        if (!empty($param)) {

            foreach ($param as $key => $vo) {
                $sql .= ' AND `' . $key . '`="' . $vo . '"';
            }
        }

        // echo $sql . PHP_EOL;
        return $sql . ';';
    }

    public static function insert($table, $param = [])
    {
        $sql = 'INSERT INTO `' . $table . '` SET ';
        if (!empty($param)) {
            foreach ($param as $key => $vo) {
                $sql .= ' `' . $key . '`="' . $vo . '",';
            }
        }

        // echo $sql . PHP_EOL;
        return rtrim($sql, ',') . ';';
    }

    public static function update($table, $param = [], $where = [])
    {
        $sql = 'UPDATE `' . $table . '` SET ';
        if (!empty($param)) {
            foreach ($param as $key => $vo) {
                $sql .= ' `' . $key . '`="' . $vo . '",';
            }
        }

        $sql = rtrim($sql, ',');
        if (!empty($where)) {

            $sql .= ' WHERE 1=1';
            foreach ($where as $key => $vo) {
                $sql .= ' AND `' . $key . '`="' . $vo . '"';
            }
        }

        // echo $sql . PHP_EOL;
        return rtrim($sql, ',') . ';';
    }

    public static function delete($table, $where = [])
    {
        $sql = 'DELETE FROM `' . $table . '` WHERE 1=1';
        if (!empty($where)) {

            foreach ($where as $key => $vo) {
                $sql .= ' AND `' . $key . '`="' . $vo . '"';
            }
        }

        // echo $sql . PHP_EOL;
        return $sql . ';';
    }
}